"use client";
import { useState, useEffect, useCallback } from 'react';
import { 
  Card, Table, Button, Input, Space, 
  Tag, Tooltip, Popconfirm, Typography, Modal, Form, Switch
} from 'antd';
import { useMessage } from '@/hooks/useMessage';
import type { TablePaginationConfig } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { adminAPI } from '@/lib/api';
import type { ProductCategory } from '@/lib/api';
import AdminLayout from '@/components/AdminLayout';

const { Text } = Typography;
const { Search } = Input;

export default function ProductCategoriesManagement() {
  const message = useMessage();
  const [categories, setCategories] = useState<ProductCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<ProductCategory | null>(null);
  const [form] = Form.useForm();

  // 获取分类列表
  const fetchCategories = useCallback(async () => {
    setLoading(true);
    try {
      const response = await adminAPI.getProductCategories();
      if (response.success) {
        setCategories(response.data);
        setPagination({
          current: 1,
          pageSize: 10,
          total: response.data.length,
        });
      }
    } catch (error) {
      console.error('获取产品分类列表失败:', error);
      message.error('获取产品分类列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 删除分类
  const handleDeleteCategory = async (id: number) => {
    try {
      const response = await adminAPI.deleteProductCategory(id);
      if (response.success) {
        message.success('删除成功');
        fetchCategories();
      }
    } catch (error) {
      console.error('删除产品分类失败:', error);
      message.error('删除失败');
    }
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理表格变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
    }));
  };

  // 处理新建分类
  const handleAddCategory = () => {
    setEditingCategory(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑分类
  const handleEditCategory = (record: ProductCategory) => {
    setEditingCategory(record);
    form.setFieldsValue({
      name: record.name,
      description: record.description,
      sort: record.sort,
      status: record.status,
    });
    setIsModalVisible(true);
  };

  // 提交表单
  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingCategory) {
        // 更新分类
        const response = await adminAPI.updateProductCategory(editingCategory.id, values);
        if (response.success) {
          message.success('分类更新成功');
        }
      } else {
        // 创建分类
        const response = await adminAPI.createProductCategory(values);
        if (response.success) {
          message.success('分类创建成功');
        }
      }
      
      setIsModalVisible(false);
      fetchCategories();
    } catch (error) {
      console.error('保存产品分类失败:', error);
      message.error('保存失败');
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchCategories();
  }, [fetchCategories]);

  // 过滤分类数据
  const filteredCategories = categories.filter(category => 
    !searchKeyword || 
    category.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
    (category.description && category.description.toLowerCase().includes(searchKeyword.toLowerCase()))
  );

  // 分页数据
  const paginatedCategories = filteredCategories.slice(
    (pagination.current - 1) * pagination.pageSize,
    pagination.current * pagination.pageSize
  );

  // 表格列定义
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
      render: (sort: number) => <Tag color="blue">{sort}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: boolean) => (
        <Tag color={status ? "green" : "red"}>
          {status ? "启用" : "禁用"}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 120,
      render: (_: unknown, record: ProductCategory) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEditCategory(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDeleteCategory(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card
        title="产品分类管理"
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddCategory}
          >
            新建分类
          </Button>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Search
            placeholder="输入关键词搜索"
            onSearch={handleSearch}
            enterButton
            style={{ width: 300 }}
          />
        </div>
        <Table
          columns={columns}
          dataSource={paginatedCategories}
          rowKey="id"
          loading={loading}
          pagination={{ ...pagination, total: filteredCategories.length }}
          onChange={handleTableChange}
          scroll={{ x: 800 }}
        />
      </Card>

      <Modal
        title={editingCategory ? '编辑分类' : '新建分类'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: true, sort: 0 }}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="分类描述"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入分类描述（可选）"
              maxLength={200}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <Input type="number" placeholder="请输入排序值" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </AdminLayout>
  );
}